import { Sequelize } from 'sequelize-typescript';
import * as SQ from 'sequelize';
import { Injectable } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { makeSalt, encryptPassword } from 'src/utils/cryptogram';

@Injectable()
export class UserService {
  constructor(private sequelize: Sequelize) {}

  create(createUserDto: CreateUserDto) {
    return 'This action adds a new user';
  }

  async findAll() {
    const sql = `
      SELECT * FROM admin_user
    `;
    try {
      const res = await this.sequelize.query(sql, {
        type: SQ.QueryTypes.SELECT,
        raw: true,
        logging: true,
      });
      return {
        code: 200,
        data: {
          users: res,
        },
      };
    } catch (error) {
      console.log(error);
      return {
        code: 503,
        msg: 'Service error on Sequelize',
      };
    }
    // return {
    //   code: 200,
    //   msg: 'getAll',
    // };
  }

  async findOne(username: string) {
    const sql = `
      SELECT
        user_id userId, account_name username, real_name realName, passwd password,
        passwd_salt salt, mobile, role
      FROM
        admin_user
      WHERE
        account_name='${username}'
    `;

    try {
      const user = (
        await this.sequelize.query(sql, {
          type: SQ.QueryTypes.SELECT,
          raw: true,
          logging: true,
        })
      )[0];

      return user;
    } catch (error) {
      console.log(error);
      return void 0;
    }
  }

  async register(requestBody: any): Promise<any> {
    const { accountName, realName, password, repassword, mobile } = requestBody;
    if (accountName === '12') {
      throw new Error('wf');
      // const accountName = '3';
    }
    if (password !== repassword) {
      return {
        code: 400,
        msg: '两次输入密码不一致',
      };
    }

    const user = await this.findOne(accountName);
    // console.log(user);
    if (user) {
      return {
        code: 400,
        msg: '用户已存在',
      };
    }

    const salt = makeSalt();
    const hashPwd = encryptPassword(password, salt);
    const reggisterSQL = `
      INSERT INTO admin_user
      (account_name, real_name, passwd, passwd_salt, mobile, user_status, role, create_by)
      VALUES
      ('${accountName}', '${realName}', '${hashPwd}', '${salt}', '${mobile}', 1, 3, 0)
    `;

    try {
      await this.sequelize.query(reggisterSQL, { logging: false });
      return {
        code: 200,
        msg: 'success',
      };
    } catch (error) {
      console.log(error);
      return {
        code: 503,
        msg: `Service error: ${error}`,
      };
    }
  }

  update(id: number, updateUserDto: UpdateUserDto) {
    return `This action updates a #${id} user`;
  }

  remove(id: number) {
    return `This action removes a #${id} user`;
  }
}
